//
//  WelcomeViewController.swift
//  新浪微博
//
//  Created by mac on 15/11/29.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

class WelcomeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        //获取头像
        iconimage.sd_setImageWithURL(UserAccountViewModel().headImageURL, placeholderImage: UIImage(named: "avatar_default_big"))
    }
    //动画效果建议在viewdidappear 方法中执行
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //执行动画效果
        startAnimation()
    }
    private func startAnimation(){
        /*
        使用自动布局需要注意
        1 所有设置自动布局的控件,在添加动画效果时,不要直接设置frame
        原因,自动布局系统会根据设置的约束,自动计算控件的frame
        2 在layoutsubviews方法中,给所有的子控件根据设置好的约束,修改相应的frame值
        3 如果主动修改frame 会引起自动布局系统计算错误
        每一次运行循环的开启,自动布局系统都会收集所有控件的约束的变化
        在运行循环结束前,调用layoutsubviews 同一一次性将所有辩护,进行更新
        
        
        如果希望提前更新,就需要调用强制刷新布局方法 layoutIfNeeded
        */
        let offset = -screenH + 180
        iconimage.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
    UIView.animateWithDuration(1.0, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 9.8, options: [], animations: { () -> Void in
        //对应已经添加的约束属性,需要修改 可以使用
        self.iconimage.snp_updateConstraints(closure: { (make) -> Void in
           self.view.layoutIfNeeded()
        })
        }) { (_) -> Void in
            //发出切换页面消息
            NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: nil)        }
    }
    private func setupUI(){
    //添加子视图
        view.addSubview(welcomeLabel)
        view.addSubview(iconimage)
        //设置布局
        iconimage.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(view.snp_centerX)
            make.bottom.equalTo(view.snp_bottom).offset(-180)
            make.size.equalTo(CGSize(width: 90, height: 90))
        }
        welcomeLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(iconimage.snp_bottom).offset(16)
            make.centerX.equalTo(iconimage.snp_centerX)
        }
        
        //设置头像圆角
        iconimage.layer.cornerRadius = 45
        iconimage.clipsToBounds = true
    }
    
//懒加载子视图
    private lazy var backimage: UIImageView = UIImageView(image: UIImage(named: "ad_background"))

//头像视图
private lazy var iconimage: UIImageView = UIImageView(image: UIImage(named: "avatar_default_big"))

//欢迎文本
    private lazy var welcomeLabel: UILabel = {
        let label = UILabel()
        label.text = (UserAccountViewModel().userName ?? "") + "欢迎归来"
        print(label.text)
        label.sizeToFit()
        label.textColor = UIColor.darkGrayColor()
        label.font = UIFont.systemFontOfSize(19)
        return label
        }()
}